//
//  DSMessViewController.m
//  DS爱信
//
//  Created by 秦建英 on 14-5-27.
//  Copyright (c) 2014年 秦建英. All rights reserved.
//
#import "DSMessViewController.h"
#import "Header.h"
#import "ChineseInclude.h"
#import "PinYinForObjc.h"
#import "DSSearchViewController.h"
#import "DingSh.h"
#import "AppDelegate.h"
#import "DSDialViewController.h"
#import "DSCallViewController.h"
#import "FMDBManager.h"
#import "NSString+FirstLetter.h"
#import "pinyin.h"
#import "ChineseString.h"
@interface DSMessViewController ()
@end
@implementation DSMessViewController
{
    NSString *_st;
    UITableView *_tabView;
    UIActivityIndicatorView *_aiv;
    NSMutableArray *_tellArray;
    NSString *_ce;
    NSString *_cs;
    NSMutableArray *_arty;
    NSMutableArray *searchResults;
    NSMutableArray *_sdt;
    NSArray *_dcg;
    NSArray *_scg;
    NSString *_hui;
    UIImageView *_imageViews;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _dataArray =[[NSArray alloc]init];
        _tellArray =[[NSMutableArray alloc]init];
        _indexArray =[[NSMutableArray alloc]init];
        _sdt =[[NSMutableArray alloc]init];
        _dcg =[[NSArray alloc]init];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addTitleviewWithTitle:@"全部联系人"];
    [searchResults removeAllObjects];
    search .hidden =NO;
    [_tabView reloadData];
    [self tabHead];
}
-(void)tabHead
{
    _imageViews =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"df.png"]];
    _imageViews.frame =CGRectMake(0, 0, DeviceWidth, 64);
    UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(0, 25, _imageViews.frame.size.width, 30)];
    label.text=@"全部联系人";
    label.textColor=[UIColor yellowColor];
    label.backgroundColor =[UIColor clearColor];
    label.textAlignment =NSTextAlignmentCenter;
    [_imageViews addSubview:label];
    [self.view addSubview:_imageViews];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [search setHidden:YES];
    [_imageViews removeFromSuperview];
    search.text =nil;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    if(_dataArray.count>0)
    {
    }
    else
    {FMDBManager* manager = [FMDBManager sharedManager];
        _dataArray = [manager getAllUsers];
        [_tabView reloadData];
    }
    if(_dataArray .count ==0)
    {
        _aiv =[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        _aiv.frame =CGRectMake(150, 190, 30, 30);
        [self.view addSubview:_aiv];
        [_aiv startAnimating];
    }
    else
    {
        [_tabView reloadData];
    }
    for(int i=0;i<[_dataArray count];i++)
    {
        NSString *fgy =((DingSh *)[_dataArray objectAtIndex:i]).name;
        [_sdt addObject:fgy];
        for(int i=0;i<[_sdt count];i++)
        {
            if ([[_sdt objectAtIndex:i] hasPrefix:@"ABMultiValueR"]) {
                [_sdt removeObject:[_sdt objectAtIndex:i]];
            }
        }
    }
    [_indexArray addObject:[ChineseString IndexArray:_sdt]];
    NSString *dgh =[_indexArray objectAtIndex:0];
    NSString *string_2 = [(NSArray *)dgh componentsJoinedByString:@","];
    _scg =[string_2 componentsSeparatedByString:@","];
    _LetterResultArr = [ChineseString LetterSortArray:_sdt];
    search =[[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, 320, 44)];
    [self.view addSubview:search];
    search.delegate =self;
    [search setPlaceholder:@"按名字首字母查询"];
    searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:search contentsController:self];
    searchDisplayController.active = NO;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    
    _tabView =[[UITableView alloc]initWithFrame:CGRectMake(0,search.frame.size.height+_imageViews.frame.size.height+64, 320, DeviceHeight-49-search.frame.size.height-_imageViews.frame.size.height-64) style:UITableViewStylePlain];
    _tabView.delegate =self;
    _tabView.dataSource =self;
    _tabView.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:_tabView];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    for(int i=0;i<[_indexArray count];i++)
    {
        _dcg =[_indexArray objectAtIndex:i];
    }
    return _dcg;
}
#pragma mark -Section的Header的值
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *key = [_scg objectAtIndex:section];
    
    return key;
}
#pragma mark - Section header view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 10)];
    lab.backgroundColor =[UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1];
    lab.text = [_scg objectAtIndex:section];
    lab.textColor = [UIColor blackColor];
    return lab;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return 1;
    }
    else{
        return [_scg count];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return searchResults.count;
    }
    else
    {
        if(_LetterResultArr.count==0)
        {
            return 0;
        }
        else
        {
            return [[_LetterResultArr objectAtIndex:section] count];
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor =[UIColor clearColor];
        UIImageView *imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tab_contacts.png"]];
        imageView.frame =CGRectMake(0, 17, 30, 30);
        [cell addSubview:imageView];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text =nil;
    cell.selectionStyle =UITableViewCellSelectionStyleGray;
    cell.textLabel.textColor =[UIColor blackColor];
    cell.textLabel.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:16];
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        cell.textLabel.text =[NSString stringWithFormat:@"      %@",[searchResults objectAtIndex:indexPath.row]];
    }
    else
    {
        cell.textLabel.text =[NSString stringWithFormat:@"     %@",[[_LetterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
    }
    [_aiv stopAnimating];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DSCallViewController *call =[[DSCallViewController alloc]init];
    if(searchResults.count>0)
    {
        _ce =[searchResults objectAtIndex:indexPath.row];
        for(int i=0;i<[_dataArray count];i++)
        {
            NSString *name =((DingSh *)[_dataArray objectAtIndex:i]).name;
            NSString *tel =((DingSh *)[_dataArray objectAtIndex:i]).tel;
            NSMutableArray *cey =[[NSMutableArray alloc]initWithObjects:name,tel, nil];
            if([_ce isEqualToString:[cey objectAtIndex:0]])
            {
                _cs=[NSString stringWithFormat:@"   %@   %@",[cey objectAtIndex:0],[cey objectAtIndex:1]];
            }
        }
        call.array =_cs;
    }
    else
    {
        _st =[NSString stringWithFormat:@"     %@",[[_LetterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
        for(int i=0;i<[_dataArray count];i++)
        {
            NSString *name =((DingSh *)[_dataArray objectAtIndex:i]).name;
            NSString *trimmed =[name stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSString *tel =((DingSh *)[_dataArray objectAtIndex:i]).tel;
            NSMutableArray *cey =[[NSMutableArray alloc]initWithObjects:trimmed,tel, nil];
            NSString *res=[_st stringByReplacingCharactersInRange:NSMakeRange(0, 5) withString:@""];
            if([res isEqualToString:[cey objectAtIndex:0]])
            {
                _cs=[NSString stringWithFormat:@"   %@   %@",[cey objectAtIndex:0],[cey objectAtIndex:1]];
            }
        }
        call.array =_cs;
    }
    NSLog(@"%@",call.array);
    UINavigationController *nvc =[[UINavigationController alloc]initWithRootViewController:call];
    [self presentViewController:nvc animated:YES completion:^{
    }];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchResults removeAllObjects];
    [_tabView reloadData];
    [searchBar resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    searchResults = [[NSMutableArray alloc]init];
    if (search.text.length>0&&![ChineseInclude isIncludeChineseInString:search.text])
    {
        for (int i=0; i<[_dataArray count]; i++)
        {
            if ([ChineseInclude isIncludeChineseInString:((DingSh *)[_dataArray objectAtIndex:i]).name])
            {
                NSString *fvd =[NSString stringWithFormat:@"%s",[[search.text firstLetter] UTF8String]];
                NSString *fgv =[fvd uppercaseString];
                NSRange titleResult=[((DingSh *)[_dataArray objectAtIndex:i]).name rangeOfString:fgv];
                if (titleResult.length>0)
                {
                    [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:i]).name];
                }
                NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:((DingSh *)[_dataArray objectAtIndex:i]).name];
                NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:search.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0)
                {
                    [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:i]).name];
                }
            }
            else {
                NSRange titleResult=[((DingSh *)[_dataArray objectAtIndex:i]).name rangeOfString:search.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0)
                {
                    [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:i]).name];
                }
            }
        }
    }
    if (search.text.length>0&&[ChineseInclude isIncludeChineseInString:search.text])
    {
        for(int j=0;j<[_dataArray count];j++)
        {
            NSRange titleResult=[((DingSh *)[_dataArray objectAtIndex:j]).name rangeOfString:search.text];
            if (titleResult.length>0)
            {
                [searchResults addObject:((DingSh *)[_dataArray objectAtIndex:j]).name];
            }
        }
    }
    [_tabView reloadData];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end
